//@ts-nocheck
import { useFocusEffect, useNavigationState } from "@react-navigation/native";
import { useCallback, useMemo, useRef, useState, useEffect } from "react";
import Decimal from "decimal";
import {
  StatusBar,
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
  TouchableOpacity,
  TextInput,
  ScrollView,
  AppState,
  type AppStateStatus,
} from "react-native";
import LinearGradient from "react-native-linear-gradient";
import { useAppSelector } from "app/store";
import { determineCurrentDevice, getStorageData } from "utils";
import toast from "utils/toast";
import { manager } from "utils/bleManage";
import iconv from "@vscode/iconv-lite-umd";
import { Characteristic } from "react-native-ble-plx";
import translate from "utils/translate";
const Buffer = require("@craftzdog/react-native-buffer").Buffer;
function gbkHexToString(hexString: string) {
  // 将十六进制字符串转换为 Buffer
  const buffer = Buffer.from(hexString, "hex");
  // 将 Buffer 转换为字符串
  const result = iconv.decode(buffer, "gbk");
  return result;
}
function areArraysEqual(arr1, arr2) {
  // 判断数组长度是否相同
  if (arr1.length !== arr2.length) {
    return false;
  }

  // 判断每个元素是否相同
  for (let i = 0; i < arr1.length; i++) {
    // 注意：这里假设数组中的元素是对象，如果元素是基本类型，可以使用严格相等（===）比较
    if (!isObjectEqual(arr1[i], arr2[i])) {
      return false;
    }
  }

  return true;
}

// 判断两个对象是否相等
function isObjectEqual(obj1, obj2) {
  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);

  // 判断属性数量是否相同
  if (keys1.length !== keys2.length) {
    return false;
  }

  // 判断每个属性的值是否相同
  for (let key of keys1) {
    if (obj1[key] !== obj2[key]) {
      return false;
    }
  }

  return true;
}
export default ({ navigation, route: { params } }: RootStackScreenProps) => {
  const state = useNavigationState((state) => state);
  const connectedDevice = useAppSelector((state) => {
    return state.app.connectedDevice;
  });
  const currentRoute = useAppSelector((state) => {
    return state.app.currentRoute;
  });
  function hexToBinary(hexString) {
    // 将每个十六进制字符映射到四位二进制字符串
    const hexToBinaryMap = {
      "0": "0000",
      "1": "0001",
      "2": "0010",
      "3": "0011",
      "4": "0100",
      "5": "0101",
      "6": "0110",
      "7": "0111",
      "8": "1000",
      "9": "1001",
      A: "1010",
      B: "1011",
      C: "1100",
      D: "1101",
      E: "1110",
      F: "1111",
    };

    // 将每个十六进制字符转换为对应的四位二进制字符串
    const binaryArray = hexString
      .split("")
      .map((hexChar) => hexToBinaryMap[hexChar.toUpperCase()]);

    // 将二进制字符串连接在一起
    const binaryString = binaryArray.join("");

    return binaryString;
  }
  useEffect(() => {
    const unsubscribe = navigation.addListener("focus", () => {
      if (currentRoute === "total") {
        setActived((pre) => {
          return {
            ...pre,
            nums: false,
          };
        });
      } else {
        lastPrice.current = "";
      }
    });
    return () => {
      unsubscribe();
    };
  }, [currentRoute, navigation, state]);
  // 示例使用
  const currentCharacteristics = useRef<Characteristic>();
  const [isActive, setActived] = useState({
    nums: false,
    price: false,
    goods: false,
  });
  const [nums, setNums] = useState("");
  // const [routeIndex, setRouteIndex] = useState(0);
  const [deviceInfo, setDeviceInfo] = useState({
    plus: true,
  });
  const Subscription = useRef();
  const [goodsList, setGoodsList] = useState([]);
  const [goodsIndex, setGoodsIndex] = useState(0);
  const pressNumsKey = useRef("");
  const [price, setPrice] = useState("0.00");
  const point = useRef("0.00");
  const lastPrice = useRef("");
  // 设置一个标记
  useEffect(() => {
    const appStateListener = async (newAppState: AppStateStatus) => {
      if (currentRoute === "specification") {
        if (newAppState === "active") {
          if (connectedDevice) {
            if (!isActive.nums) {
              getData();
            }
          } else {
            toast(translate("main.connectTip"));
          }
        } else {
          if (!isActive.nums) {
            currentCharacteristics.current
              ?.writeWithResponse(Buffer.from("A2", "hex").toString("base64"))
              .then(() => {
                Subscription.current.remove();
                setTimeout(() => {
                  setNums("");
                }, 100);
                // toast(translate("main.StopWeighingSuccess"));
              });
          }
        }
      }
    };
    const subscription = AppState.addEventListener("change", appStateListener);
    return () => {
      subscription.remove();
    };
  }, [currentRoute, isActive.nums, connectedDevice]);
  useFocusEffect(
    useCallback(() => {
      if (connectedDevice) {
        if (!isActive.nums) {
          getData();
        }
        getStorageData("classList").then((classList) => {
          getStorageData("defaultGoods").then((value) => {
            if (value) {
              const currentItem = JSON.parse(classList)?.find(
                (item) => item.id == value
              );
              point.current = currentItem.point;
              !areArraysEqual(currentItem?.goodsList ?? [], goodsList) &&
                setGoodsList(currentItem?.goodsList ?? []);
            } else {
              toast(translate("main.SelectTip"));
              point.current = "0.00";
              !areArraysEqual([], goodsList) && setGoodsList([]);
            }
          });
        });
        if (params?.index || params?.index === 0) {
          setGoodsIndex(() => {
            return params.index;
          });
        }
      } else {
        toast(translate("main.connectTip"));
        setNums("");
      }
      return () => {
        if (!isActive.nums) {
          currentCharacteristics.current
            ?.writeWithResponse(Buffer.from("A2", "hex").toString("base64"))
            .then(() => {
              Subscription.current.remove();
              setTimeout(() => {
                setNums("");
              }, 100);
              // toast(translate("main.StopWeighingSuccess"));
            });
        }
      };
    }, [connectedDevice, isActive.nums, params])
  );
  useFocusEffect(
    useCallback(() => {
      if (goodsList.length > 0) {
        setPrice((pre) => {
          return pre === lastPrice.current
            ? pre
            : goodsList[goodsIndex]?.price ?? point.current;
        });
      } else {
        setPrice(lastPrice.current || point.current);
      }
    }, [goodsIndex, goodsList, point.current, lastPrice.current])
  );
  const keyboardRight = [
    {
      label: translate("main.zero"),
      onClick: () => {
        currentCharacteristics.current
          ?.writeWithResponse(
            Buffer.from("3C5A004B3E09", "hex").toString("base64")
          )
          .then(() => {
            toast(translate("main.success"));
          });
      },
    },
    {
      label: translate("main.peelKey"),
      onClick: () => {
        currentCharacteristics.current
          ?.writeWithResponse(
            Buffer.from("3C54004B3E09", "hex").toString("base64")
          )
          .then(() => {
            toast(translate("main.success"));
          });
      },
    },
    {
      label: translate("main.del"),
      onClick: () => {
        if (isActive.nums) {
          setNums("");
        } else {
          setPrice(point.current);
        }
        pressNumsKey.current = "";
      },
    },
    {
      label: translate("scale.total"),
      onClick: () => {
        // setPrice(point.current);
        lastPrice.current = price;
        pressNumsKey.current = "";
        navigation.navigate(
          "total",
          Number(total) === 0 || isNaN(Number(total)) || !deviceInfo.plus
            ? {}
            : {
                nums: nums.replace(/^0+(?=\d)/, "") ?? "0.000",
                price: price,
                goodsName:
                  goodsList[goodsIndex]?.goodsName ||
                  translate("main.TemporaryGoods"),
                total,
                createTime: new Date().valueOf(),
                isNums: isActive.nums,
              }
        );
      },
    },
  ];
  const keyboardLeft = [
    {
      label: translate("main.set"),
      onClick: () => {
        if (!connectedDevice) return toast(translate("main.connectTip"));
        navigation.navigate("settings", {});
        pressNumsKey.current = "";
      },
    },
    {
      label: "0",
      onClick: () => {
        onPressNums("0");
      },
    },
    {
      label: ".",
      onClick: () => {
        onPressNums(".");
      },
    },
  ];
  const getData = async () => {
    setNums("");
    const services = await manager
      .discoverAllServicesAndCharacteristicsForDevice(connectedDevice as string)
      .then((device) => {
        return device.services();
      })
      .catch((err) => {
        toast(JSON.stringify(err) ?? translate("main.error"));
      });
    if (services) {
      const item = determineCurrentDevice(services);
      if (item) {
        const characteristicsList = await item.characteristics();
        for (let current of characteristicsList) {
          if (current.isWritableWithResponse && current.isNotifiable) {
            Subscription.current = current.monitor((err, characteristic) => {
              if (err && err.reason) {
                // toast(err.reason, 5 * 1000);
                setNums("----");
                return Subscription.current.remove();
              }
              if (characteristic?.value) {
                const hexValue: string = Buffer.from(
                  JSON.stringify(characteristic.value),
                  "base64"
                ).toString("hex");
                const reg = /^0102/;
                const formatValue = hexValue.replace(reg, "");
                const state = hexToBinary(formatValue.slice(-2));
                const zeroStatus = state.at(3) === "1" ? true : false;
                const drop = state.at(2) === "1" ? true : false;
                const arr = [
                  "weightStatus",
                  "plus",
                  "weight",
                  "unit",
                  "battery",
                ];
                const List = arr.map((item, index) => {
                  if (index === 0) {
                    return [item, gbkHexToString(formatValue.slice(0, 2))];
                  } else if (index === 1) {
                    return [
                      item,
                      formatValue.slice(2, 4) == "20" ? true : false,
                    ];
                  } else if (index === 2) {
                    return [item, gbkHexToString(formatValue.slice(4, 16))];
                  } else if (index === 3) {
                    return [item, gbkHexToString(formatValue.slice(16, 20))];
                  } else if (index === 4) {
                    return [
                      item,
                      gbkHexToString(formatValue.slice(20, 24)) / 10,
                    ];
                  }
                });
                const { weight, ...rest } = Object.fromEntries(List);
                !isActive.nums && setNums(weight);
                setDeviceInfo((pre) => {
                  return {
                    ...pre,
                    ...rest,
                    zeroStatus,
                    drop,
                  };
                });
              }
            });
            currentCharacteristics.current = current;
            return current.writeWithResponse(
              Buffer.from("A1", "hex").toString("base64")
            );
          }
        }
      } else {
        toast(translate("main.error"));
      }
    }
  };
  const onPressNums = (value) => {
    if (isActive.nums) {
      setNums((pre) => {
        if (isNaN(+pre)) {
          return "" + value;
        } else {
          return (pre += value);
        }
      });
    } else {
      setPrice(!pressNumsKey.current ? value + "" : price + value);
      pressNumsKey.current = pressNumsKey.current + value;
    }
  };
  const total = useMemo(() => {
    if (!isNaN(+nums)) {
      return deviceInfo.plus
        ? Decimal(price || "0.00")
            .mul(nums || "0.000")
            .toNumber()
            .toFixed(2)
        : "----";
    } else {
      return "0.00";
    }
  }, [deviceInfo, nums, price]);
  return (
    <LinearGradient
      colors={["#0181FE", "#F3F6F9", "#F3F6F9"]}
      useAngle
      angle={180}
      style={styles.container}
    >
      <StatusBar hidden></StatusBar>
      <ScrollView
        style={{
          marginTop: 4,
        }}
      >
        <View style={styles.overview}>
          <View
            style={{
              width: 263,
              alignSelf: "center",
              paddingTop: 16,
              paddingBottom: 12,
            }}
          >
            <View
              style={{
                flexDirection: "row",
                justifyContent: "space-between",
                marginBottom: 20,
              }}
            >
              <View
                style={{
                  alignItems: "center",
                }}
              >
                <Text
                  style={{
                    color: "#EE1D1D",
                    fontWeight: "700",
                    fontSize: 32,
                    fontFamily: "D-DIN-Bold",
                  }}
                >
                  {/* {(deviceInfo?.plus ? "" : "-") +
                    (nums?.replace(/^0+(?=\d)/, "") ||
                      (isActive.nums ? "0" : "----"))} */}
                  {connectedDevice
                    ? isActive.nums
                      ? nums
                        ? nums?.replace(/^0+(?=\d)/, "")
                        : "0"
                      : nums
                        ? (deviceInfo?.plus ? "" : "-") +
                          nums?.replace(/^0+(?=\d)/, "")
                        : "0.000"
                    : isActive.nums
                      ? nums
                        ? nums?.replace(/^0+(?=\d)/, "")
                        : "0"
                      : "----"}
                </Text>
                <Text
                  style={{
                    marginBottom: 12,
                  }}
                >
                  {translate("main.quantityWei")}
                </Text>
                {/* <Text style={styles.item}>
                  <Text
                    style={{
                      color: "#00000099",
                    }}
                  >
                    皮重：
                  </Text>
                  0.000kg
                </Text> */}
                <Text
                  style={{
                    fontSize: 16,
                    fontWeight: "500",
                    // borderBottomWidth: 1,
                    // borderColor: "#f0f0f0",
                    paddingBottom: 12,
                  }}
                >
                  {goodsList?.[goodsIndex]?.goodsName ||
                    translate("main.TemporaryGoods")}
                  {/* 临时商品 */}
                </Text>
              </View>
              <View
                style={{
                  alignItems: "center",
                }}
              >
                <Text
                  style={{
                    color: "#EE1D1D",
                    fontWeight: "700",
                    fontSize: 32,
                    fontFamily: "D-DIN-Bold",
                  }}
                >
                  <Text
                    style={{
                      fontSize: 20,
                    }}
                  >
                    ￥
                  </Text>
                  {total}
                </Text>
                <Text
                  style={{
                    marginBottom: 12,
                  }}
                >
                  {translate("main.amount")}
                </Text>
                <Text style={styles.item}>
                  <Text
                    style={{
                      color: "#00000099",
                    }}
                  >
                    {translate("class.price")}：
                  </Text>
                  {/* 0.00元 */}
                  {price}
                  {/* <TextInput value={goodsList.current?.price}></TextInput> */}
                </Text>
              </View>
            </View>
            <TouchableHighlight
              style={styles.button}
              onPress={() => {
                if (!goodsList.length > 0) {
                  toast(translate("main.SelectTip"));
                } else {
                  navigation.navigate("goodsList", {});
                }
                pressNumsKey.current = "";
              }}
            >
              <Text
                style={{
                  color: "#0181fe",
                }}
              >
                {translate("main.product")}
              </Text>
            </TouchableHighlight>
          </View>
          <View
            style={{
              flexDirection: "row",
              alignItems: "center",
              justifyContent: "space-between",
              borderTopWidth: 1,
              borderColor: "#f0f0f0",
              paddingTop: 8,
            }}
          >
            <View
              style={{
                flexDirection: "row",
                alignItems: "center",
              }}
            >
              <View
                style={{
                  flexDirection: "row",
                  alignItems: "center",
                  position: "relative",
                  paddingLeft: 12,
                }}
              >
                <View
                  style={{
                    ...styles.dot,
                    backgroundColor:
                      deviceInfo.weightStatus === "S" ? "#F59A23" : "#7F7F7F",
                  }}
                ></View>
                <Text>{translate("main.stabilize")}</Text>
              </View>
              <View
                style={{
                  flexDirection: "row",
                  alignItems: "center",
                  position: "relative",
                  paddingLeft: 12,
                  marginLeft: 12,
                  marginRight: 12,
                }}
              >
                <View
                  style={{
                    ...styles.dot,
                    backgroundColor: deviceInfo.drop ? "#F59A23" : "#7F7F7F",
                  }}
                ></View>
                <Text>{translate("main.peel")}</Text>
              </View>
              <View
                style={{
                  flexDirection: "row",
                  alignItems: "center",
                  paddingLeft: 12,
                  position: "relative",
                }}
              >
                <View
                  style={{
                    ...styles.dot,
                    backgroundColor: deviceInfo.drop ? "#0181FE" : "#7F7F7F",
                  }}
                ></View>
                <Text>{translate("main.zero")}</Text>
              </View>
            </View>
            <Text>
              {translate("main.Electric")}：{deviceInfo?.battery ?? "---"}v
            </Text>
          </View>
        </View>
        <View
          style={{
            flexDirection: "row",
            height: 255,
            width: "100%",
            backgroundColor: "#fff",
            marginTop: 12,
            borderColor: "#eeeeee",
            borderTopWidth: 1,
            borderBottomWidth: 1,
          }}
        >
          <View
            style={{
              flexDirection: "row",
              flex: 3,
              flexWrap: "wrap",
            }}
          >
            {new Array(9).fill(undefined).map((_, index) => {
              return (
                <TouchableOpacity
                  key={index}
                  style={{
                    width: `${100 / 3}%`,
                    height: "25%",
                    alignItems: "center",
                    justifyContent: "center",
                    borderColor: "#eeeeee",
                    borderBottomWidth: 1,
                    borderLeftWidth: 1,
                  }}
                  onPress={() => {
                    onPressNums(index + 1);
                  }}
                >
                  <Text
                    style={{
                      fontSize: 24,
                      fontWeight: "500",
                    }}
                  >
                    {index + 1}
                  </Text>
                </TouchableOpacity>
              );
            })}
            {keyboardLeft.map((item, index) => {
              return (
                <TouchableOpacity
                  onPress={index >= 1 ? item.onClick : undefined}
                  key={item.label}
                  style={{
                    width: `${100 / 3}%`,
                    height: "25%",
                    alignItems: "center",
                    justifyContent: "center",
                    borderColor: "#eeeeee",
                    borderLeftWidth: 1,
                  }}
                  delayLongPress={1000}
                  onLongPress={index === 0 ? item.onClick : undefined}
                >
                  <Text
                    style={{
                      fontSize: index === 0 ? 16 : 24,
                      fontWeight: "500",
                    }}
                  >
                    {item.label}
                  </Text>
                </TouchableOpacity>
              );
            })}
          </View>
          <View
            style={{
              flex: 1,
              borderColor: "#eeeeee",
              borderLeftWidth: 1,
            }}
          >
            {keyboardRight.map((item, index) => {
              return (
                <TouchableOpacity
                  key={item.label}
                  onPress={item.onClick}
                  style={{
                    width: `100%`,
                    height: "25%",
                    alignItems: "center",
                    justifyContent: "center",
                    borderColor: "#eeeeee",
                    borderBottomWidth: index === 3 ? 0 : 1,
                  }}
                >
                  <Text
                    style={{
                      fontSize: 16,
                      fontWeight: "500",
                    }}
                  >
                    {item.label}
                  </Text>
                </TouchableOpacity>
              );
            })}
          </View>
        </View>
        <View
          style={{
            flexDirection: "row",
            justifyContent: "space-around",
            marginTop: 16,
          }}
        >
          <TextInput
            placeholder={translate("main.code")}
            style={{
              width: 231,
              height: 36,
              backgroundColor: "#ffffff",
              borderColor: "#0181fe",
              borderWidth: 1,
              borderRadius: 4,
              paddingHorizontal: 8,
              color: "#333",
            }}
            // value={nums}
            editable={false}
          ></TextInput>
          <TouchableOpacity
            style={{
              ...styles.bottomBtn,
              backgroundColor: isActive.nums
                ? "rgba(1, 129, 254, 0.1)"
                : "#0000001a",
              borderWidth: isActive.nums ? 1 : 0,
            }}
            onPress={() => {
              setActived((pre) => {
                return {
                  nums: !pre.nums,
                  price: false,
                  goods: false,
                };
              });
              pressNumsKey.current = "";
            }}
          >
            <Text
              style={{
                fontWeight: "500",
                color: isActive.nums ? "#0181fe" : "#fff",
              }}
            >
              {translate("main.quantity")}
            </Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </LinearGradient>
  );
};
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  overview: {
    backgroundColor: "#ffffff",
    borderRadius: 12,
    marginLeft: 16,
    marginRight: 16,
    marginTop: 10,
    paddingTop: 12,
    paddingBottom: 12,
    paddingLeft: 16,
    paddingRight: 16,
  },
  button: {
    width: "100%",
    height: 40,
    borderColor: "#0181fe",
    borderWidth: 1,
    borderRadius: 22,
    justifyContent: "center",
    alignItems: "center",
  },
  item: {
    width: 100,
    height: 30,
    backgroundColor: "#F3F6F9",
    borderRadius: 2,
    textAlign: "center",
    lineHeight: 30,
    fontSize: 13,
  },
  dot: {
    width: 9,
    height: 9,
    borderRadius: 4.5,
    position: "absolute",
    top: "36%",
  },
  bottomBtn: {
    borderColor: "#0181fe",
    width: 96,
    height: 36,
    justifyContent: "center",
    alignItems: "center",
    borderRadius: 4,
  },
});
